<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Channel;
use app\model\Customer;
use app\model\Principal;

class FeedBossReport extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function read(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedbossreport:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$where = [];
		$ocpc = [];
		$expand = [];
		$access = [];
		$copy = [];
		$limit = $request->param('limit/d', 20);

		array_push( $access, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $copy, ['companyId', '=', $request->sessInfo['companyId'] ] );

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['campaignid', '>', 0 ] );
		array_push( $where, ['userType', '=', 2 ] );

		array_push( $expand, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $expand, ['campaignid', '>', 0 ] );
		array_push( $expand, ['userType', '=', 2 ] );

		array_push( $ocpc, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $ocpc, ['userType', '=', 2 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $access, ['bazaarId', '=', $bazaarId ] );
			array_push( $expand, ['bazaarId', '=', $bazaarId ] );
			array_push( $where, ['bazaarId', '=', $bazaarId ] );
			array_push( $ocpc, ['bazaarId', '=', $bazaarId ] );
			array_push( $copy, ['bazaarId', '=', $bazaarId ] );
		}

		$userid = $request->param('userid', '', 'trim');
		if($userid) {
			array_push( $where, ['userid', '=', $userid ] );
			array_push( $expand, ['userid', '=', $userid ] );
			array_push( $copy, ['userid', '=', $userid ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			array_push( $access, ['accessTime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, false) ] );
			array_push( $where, ['datatime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, true) ] );
			array_push( $expand, ['datatime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, true) ] );
			array_push( $ocpc, ['ocpcTime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, false) ] );
			array_push( $copy, ['copyTime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, false) ] );
		} else {
			array_push( $access, ['accessTime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), false) ] );
			array_push( $where, ['datatime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true) ] );
			array_push( $expand, ['datatime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true) ] );
			array_push( $ocpc, ['ocpcTime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), false) ] );
			array_push( $copy, ['copyTime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), false) ] );
		}

		$searchArray = Db::table('cfg_search')->field('`userid`, sum(`cost`) as `cost`, avg(`rebate`) as `rebate`, sum(`cash`) as `cash`,
			sum(`impression`) as `impression`, sum(`clicks`) as `clicks`, sum(`cpc`) as `cpc`, ROUND(sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			 sum(`copynumber`) as `copynumber`, IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
				 ->where($where)->group('userid')->select()->toArray();

		foreach ($where as $key => $value) {
			if (in_array('datatime', $value)) {
				unset($where[$key]);
			}
			if (in_array('campaignid', $value)) {
				unset($where[$key]);
			}
		}

		foreach ($expand as $key => $value) {
			if (in_array('datatime', $value)) {
				unset($expand[$key]);
			}
			if (in_array('campaignid', $value)) {
				unset($expand[$key]);
			}
		}

		$channelid = $request->param('channelid', '', 'trim');
		if($channelid) {
			array_push( $expand, ['channelid', '=',  $channelid ] );
		}

		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $expand, ['customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $expand, ['contact', '=',  $contact ] );
		}

		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $expand, ['userid', 'in',  $authaccount ] );
			}
		}
		$paginate = Db::name('cfg_expand')->field('id, userid, username, password, token, contact, bazaarId, domainIds, userStat, countStat, budget, balance, rebate, lastDatetime')
		 ->where($expand)->order('lastDatetime', 'desc')->paginate($limit);

		$total = $paginate->total();
		$items = $paginate->items();
		foreach ( $items as &$value ) {
			$value['cost'] = 0;
			$value['cash'] = 0;
			$value['impression'] = 0;
			$value['copynumber'] = 0;
			$value['copycost'] = 0;
			$value['clicks'] = 0;
			$value['cpc'] = 0;
			$value['ctr'] = 0;
			$value['rebate'] = $value['rebate'];
			$value['copycostex'] = 0;
			$value['copynumberex'] = Db::table('cfg_copy')->where($copy)->where('userid', $value['userid'])->count();
			$value['accessnumber'] = Db::table('cfg_access')->where($access)->where('userid', $value['userid'])->count();
			$value['ocpc'] = Db::table('cfg_copy')->where($ocpc)->where('userid', $value['userid'])->where('ocpcStatus', 5)->count();
			$search = cloud_get_array($searchArray, $value['userid'], 'userid');
			if( is_array($search) ) {
				$value['copycostex'] = $this->cashPrice($search['cost'], $value['copynumberex']);
				$value['rebate'] = $search['rebate'] ? $search['rebate'] : $value['rebate'];
				$value['impression'] = $search['impression'];
				$value['copynumber'] = $search['copynumber'];
				$value['copycost'] = $search['copycost'];
				$value['clicks'] = $search['clicks'];
				$value['cost'] = $search['cost'];
				$value['cash'] = $search['cash'];
				$value['cpc'] = $search['cpc'];
				$value['ctr'] = $search['ctr'];
			}
		}

		return json(['code'=> 0, 'msg'=> '', 'count'=> $total, 'data'=> $items,
			'expand' => Expand::getAuthList($request->sessInfo, 2),
		  'channel' => Channel::getList($request->sessInfo),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 2) ]);
	}

	/**
	 * 成本计算
	 *
	 * @return
	 */
	protected function cashPrice($term, $price ) {
		if( $term <= 0 ) {
			return $price;
		}
		$result = bcdiv($price, $term, 2);
		return $result;
	}

	/**
	 * 获取账号推广地域
	 *
	 * @return
	 */
	public function getAccountInfo(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedbossreport:region')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$updateAccountInfo = [
			'header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
			'body'=> [
				'accountFields' =>	[
					'regionTarget'
				]
			]
		];
		$result = doPostRequest('https://api.baidu.com/json/sms/service/AccountService/getAccountInfo', json_encode($updateAccountInfo));
		if(empty($result)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}

		$response = json_decode($result, true);
		if(!is_array($response)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}

		if(!isset($response['header'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}

		if(!isset($response['header']['desc'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}

		if($response['header']['desc'] == 'success') {
			if(count($response['body']['data'][0]['regionTarget']) == 0){
				return ['code'=> 403, 'msg'=> '未设置推广地域!'];
			}
			return ['code'=> 0, 'msg'=> '操作成功!', 'regionTarget'=> $response['body']['data'][0]['regionTarget']];
		}

		if(!isset($response['header']['failures'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		return ['code'=> 403, 'msg'=> $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
	}

}
